<?php
include_once(__DIR__ . './api/baseSQL.php');

class Page extends BaseSql
{  
    //属性
    public $total;                         //数据表中总记录数
    public $pageSize;                      //每页显示行数
    public $sql;                         //SQL语句使用limit从句,限制获取记录个数
    public $sql2;                         //SQL语句使用limit从句,限制获取记录个数
    public $currentPage;                          //当前页  
    function __construct($pageSize, $currentPage)
    {
        //初始化属性
        $this->pageSize = $pageSize;
        $this->currentPage = $currentPage;
        $this->dsn = $this->dbms . ":host=" . $this->host .  ";dbname=" . $this->dbName;
    }

    function setSql($sql, $sql2)
    {
        $startPos = ($this->currentPage - 1) * $this->pageSize;
        $this->sql = $sql . ' limit ' . $startPos. ', ' .$this->pageSize;
        $this->sql2 = $sql2;
    }

    function getData():array
    {


        try {
            $dbh = new PDO($this->dsn, $this->user, $this->pass); //初始化一个PDO对象


            $stmt = $dbh->query($this->sql, PDO::FETCH_ASSOC);

            $result = $stmt->fetchAll();
            
            $stmt = $dbh->query($this->sql2, PDO::FETCH_ASSOC);
            $tmp = $stmt->fetch();
            $this -> total = $tmp['COUNT(*)'];
            
            $dbh=null;
            if ($this -> total > 0){
                return [
                    'total' => $this -> total,
                    'pageSize' => $this -> pageSize,
                    'table' => $result
                ];

            }
            else{
                return [
                    'total' => $this -> total,
                    'pageSize' => $this -> pageSize,
                ];

            }

        } catch (PDOException $e) {
            // die("Error!: " . $e->getMessage() . "<br/>");
            
            return [
            ];
        }
    }



    function show()
    {
        return $this -> getData();
    }
}

